package com.topchain.licenceverify.utils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

public class IPUtils {

    /**
     * 获取本地IP地址
     *
     * @throws SocketException
     */
    public static List<String> getLocalIp() throws UnknownHostException, SocketException {
        if (isWindows()) {
            return getWindowsIp();
        } else {
            return getLinuxIp();
        }
    }

    /**
     * 是否是Windows操作系统
     *
     * @return
     */
    public static boolean isWindows() {
        boolean isWindows = false;
        String os = System.getProperty("os.name");
        if (os != null && os.toLowerCase().indexOf("windows") > -1) {
            isWindows = true;
        }
        return isWindows;
    }

    /**
     * 获取Windows下的IP地址
     *
     * @return
     * @throws UnknownHostException
     */
    public static List<String> getWindowsIp() throws UnknownHostException {
        List<String> ipList = new ArrayList<>();
        ipList.add(InetAddress.getLocalHost().getHostAddress());
        return ipList;
    }

    /**
     * 获取Linux下的IP地址
     *
     * @return IP地址
     * @throws SocketException
     */
    private static List<String> getLinuxIp() throws SocketException {
        List<String> ipList = new ArrayList<>();

        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {
            NetworkInterface netInterface = networkInterfaces.nextElement();
            String name = netInterface.getName();

            if (name != null && !name.contains("docker") && !name.contains("lo")) {
                Enumeration<InetAddress> inetAddresses = netInterface.getInetAddresses();

                while (inetAddresses.hasMoreElements()) {
                    InetAddress inetAddress = inetAddresses.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        String ip = inetAddress.getHostAddress();
                        if (ip != null && !ip.contains("::") && !ip.contains("0:0:") && !ip.contains("fe80")) {
                            ipList.add(ip);
                        }
                    }
                }
            }
        }
        return ipList;
    }
}
